package practise;

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

public class 案例四 {
    static Scanner scanner = new Scanner(System.in);

//    自己写的复杂代码，有错误
//    public static void main(String[] args) throws Exception{
//        OutputStream outputStream = new FileOutputStream("day10/src/practise/file/data.txt");
//        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
//        PrintStream printStream = new PrintStream(bufferedOutputStream);
//        System.out.print("输入3个验证码:");
//        for (int i =0 ; i < 3 ; i++) {
//            printStream.println(scanner.nextLine().getBytes());
//        }
//        bufferedOutputStream.close();
//        System.out.print("输入一个验证码:");
//        String verificationCode = scanner.nextLine();
//
//        Reader reader = new FileReader("day10/src/practise/file/data.txt");
//        BufferedReader bufferedReader = new BufferedReader(reader);
//        boolean flag = false;
//        for (int i = 0 ; i < 3 ; i++) {
//            String test = bufferedReader.readLine();
//            if (verificationCode.equals(test)) {
//                System.out.println("验证成功!");
//                flag = true;
//                break;
//            }
//        }
//        if (!flag) {
//            System.out.println("验证失败!");
//        }
//        bufferedOutputStream.close();
//    }


public static void main(String[] args) throws Exception {
    writeToFile();  // 写入三个验证码
    verificationCode(); //　写入验证码
}

    public static void verificationCode() throws Exception{
        BufferedReader bufferedReader = // 高级输入流
                new BufferedReader(new FileReader(new File("day10/src/practise/file/data.txt")));
        ArrayList<String> strings = new ArrayList<>();  // 存储已存在的三个验证码
        System.out.print("请输入你的验证码:");
        String verification = scanner.nextLine();
        String ty = null;
//        读取一行数据，写入集合中
        while ((ty = bufferedReader.readLine())!=null) {
            strings.add(ty);
        }
        System.out.println(strings);
        if (strings.contains(verification)) { // 如果
            System.out.println("验证成功");
        } else {
            System.out.println("验证失败");
        }
        bufferedReader.close();
    }



    public static void writeToFile() throws Exception{
        BufferedWriter bufferedWriter = // 写入，高级字符输出流
                new BufferedWriter(new FileWriter(new File("day10/src/practise/file/data.txt")));
        for (int i =0 ;i < 3 ; i++) {
            System.out.print("输入第"+(i+1)+"个验证码:");
            bufferedWriter.write(scanner.nextLine());
            bufferedWriter.newLine();   // 写入新的一行（换行）
        }
        bufferedWriter.close();
    }

}
